package com.sourcestream.whileaway;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import java.util.Calendar;
import java.util.Date;

public class UserPresentReceiver extends BroadcastReceiver
{
    private static boolean screenOffReceiverRegistered = false;

    public void onReceive(Context context, Intent intent)
    {
        enableScreenOffReceiver(context);

        ReceiverManager.disableReceiver(context, PhoneStateReceiver.class);
        ReceiverManager.disableReceiver(context, SmsReceiver.class);

        SharedPreferences sp = context.getSharedPreferences("PhoneState", Context.MODE_PRIVATE);
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, -30);
        Date thirtySecondsAgo = now.getTime();

        int missedCallsCount = sp.getInt("MissedCalls", 0);

        int missedTextsCount = sp.getInt("MissedTexts", 0);
        Date lastMissedText = new Date(sp.getLong("LastMissedText", 0));
        if (lastMissedText.after(thirtySecondsAgo) && missedTextsCount == 1)
        {
            missedTextsCount = 0; //suppress missed texts if only one has been received within the last 30 seconds
        }

        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("MissedCalls", 0);
        editor.putInt("MissedTexts", 0);
        editor.remove("LastMissedText");
        editor.commit();

        if (missedCallsCount > 0 || missedTextsCount > 0)
        {
            Intent main = new Intent(context, MainActivity.class);
            main.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            main.putExtra("MissedCalls", missedCallsCount);
            main.putExtra("MissedTexts", missedTextsCount);
            context.startActivity(main);
        }
    }

    /**
     * Registers the "screen off" receiver. For some reason, this intent cannot be registered in the Android manifest
     * file so we have to do that from a service.
     *
     * @param context Context
     */
    public static void enableScreenOffReceiver(Context context)
    {
        if (!screenOffReceiverRegistered)
        {
            Intent i = new Intent(context, ScreenService.class);
            context.startService(i);
            screenOffReceiverRegistered = true;
        }
    }

    /**
     * Unregisters the "screen off" receiver and stops the screen service.
     *
     * @param context Context
     */
    public static void disableScreenOffReceiver(Context context)
    {
        if (screenOffReceiverRegistered)
        {
            ReceiverManager.disableReceiver(context, ScreenOffReceiver.class);

            Intent i = new Intent(context, ScreenService.class);
            context.stopService(i);
            screenOffReceiverRegistered = false;
        }
    }
}
